<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#4a6bff">
    <meta name="description" content="多功能计算器 - 基本和高级计算功能">
    <title>多功能计算器</title>
    <link rel="manifest" href="manifest.json">
    <link rel="apple-touch-icon" href="icons/icon-192x192.png">
    <style>
        :root {
            --primary-color: #4a6bff;
            --secondary-color: #3a5bef;
            --dark-color: #2c3e50;
            --light-color: #f5f7fa;
            --danger-color: #ff4757;
            --success-color: #2ed573;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --border-radius: 8px;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--light-color);
            color: var(--dark-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 20px;
            max-width: 1000px;
            margin: 0 auto;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }

        h1 {
            color: var(--primary-color);
            font-size: 1.8rem;
        }

        .mode-toggle {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 30px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked+.slider {
            background-color: var(--primary-color);
        }

        input:checked+.slider:before {
            transform: translateX(30px);
        }

        .tab-container {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 1rem;
            color: var(--dark-color);
            transition: all 0.3s;
            position: relative;
        }

        .tab.active {
            color: var(--primary-color);
            font-weight: bold;
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 100%;
            height: 3px;
            background-color: var(--primary-color);
        }

        .calculator {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            padding: 20px;
            margin-bottom: 20px;
            flex-grow: 1;
        }

        .display {
            background-color: #f8f9fa;
            border-radius: var(--border-radius);
            padding: 15px;
            margin-bottom: 15px;
            text-align: right;
            font-size: 2rem;
            min-height: 80px;
            word-break: break-all;
            position: relative;
        }

        .history {
            font-size: 1rem;
            color: #666;
            min-height: 20px;
            margin-bottom: 5px;
        }

        .buttons {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }

        .scientific-buttons {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        button {
            padding: 15px;
            font-size: 1.2rem;
            border: none;
            border-radius: var(--border-radius);
            background-color: #f1f3f4;
            cursor: pointer;
            transition: all 0.2s;
        }

        button:hover {
            background-color: #e1e3e4;
        }

        button:active {
            transform: scale(0.98);
        }

        .operator {
            background-color: #dfe1e5;
        }

        .equals {
            background-color: var(--primary-color);
            color: white;
        }

        .equals:hover {
            background-color: var(--secondary-color);
        }

        .clear,
        .delete {
            background-color: var(--danger-color);
            color: white;
        }

        .clear:hover,
        .delete:hover {
            background-color: #ff6b81;
        }

        .scientific {
            background-color: #e6f7ff;
        }

        .hidden {
            display: none;
        }

        footer {
            text-align: center;
            margin-top: auto;
            padding-top: 20px;
            color: #666;
            font-size: 0.9rem;
        }

        @media (max-width: 600px) {
            .buttons {
                grid-template-columns: repeat(4, 1fr);
            }

            .scientific-buttons {
                grid-template-columns: repeat(5, 1fr);
            }

            button {
                padding: 12px;
                font-size: 1rem;
            }

            .display {
                font-size: 1.5rem;
                min-height: 60px;
            }
        }

        /* 暗色模式 */
        body.dark-mode {
            background-color: #121212;
            color: #e0e0e0;
        }

        body.dark-mode .calculator {
            background-color: #1e1e1e;
        }

        body.dark-mode .display {
            background-color: #2d2d2d;
            color: #ffffff;
        }

        body.dark-mode .history {
            color: #aaaaaa;
        }

        body.dark-mode button {
            background-color: #333333;
            color: #ffffff;
        }

        body.dark-mode button:hover {
            background-color: #444444;
        }

        body.dark-mode .operator {
            background-color: #555555;
        }

        body.dark-mode .scientific {
            background-color: #1a3a6e;
        }

        body.dark-mode .tab {
            color: #e0e0e0;
        }

        body.dark-mode .tab.active {
            color: var(--primary-color);
        }
    </style>
</head>

<body>
    <header>
        <h1>多功能计算器</h1>
        <div class="mode-toggle">
            <span>暗色模式</span>
            <label class="switch">
                <input type="checkbox" id="dark-mode-toggle">
                <span class="slider"></span>
            </label>
        </div>
    </header>

    <div class="tab-container">
        <button class="tab active" data-tab="basic">基本计算</button>
        <button class="tab" data-tab="scientific">科学计算</button>
    </div>

    <div class="calculator">
        <div class="display">
            <div class="history" id="history"></div>
            <div id="display">0</div>
        </div>

        <div id="basic-calculator">
            <div class="buttons">
                <button class="clear" onclick="clearDisplay()">C</button>
                <button class="delete" onclick="deleteLastChar()">⌫</button>
                <button class="operator" onclick="appendToDisplay('%')">%</button>
                <button class="operator" onclick="appendToDisplay('/')">/</button>

                <button onclick="appendToDisplay('7')">7</button>
                <button onclick="appendToDisplay('8')">8</button>
                <button onclick="appendToDisplay('9')">9</button>
                <button class="operator" onclick="appendToDisplay('*')">×</button>

                <button onclick="appendToDisplay('4')">4</button>
                <button onclick="appendToDisplay('5')">5</button>
                <button onclick="appendToDisplay('6')">6</button>
                <button class="operator" onclick="appendToDisplay('-')">-</button>

                <button onclick="appendToDisplay('1')">1</button>
                <button onclick="appendToDisplay('2')">2</button>
                <button onclick="appendToDisplay('3')">3</button>
                <button class="operator" onclick="appendToDisplay('+')">+</button>

                <button onclick="appendToDisplay('0')">0</button>
                <button onclick="appendToDisplay('.')">.</button>
                <button class="equals" onclick="calculate()" colspan="2">=</button>
            </div>
        </div>

        <div id="scientific-calculator" class="hidden">
            <div class="buttons">
                <button class="clear" onclick="clearDisplay()">C</button>
                <button class="delete" onclick="deleteLastChar()">⌫</button>
                <button class="operator" onclick="appendToDisplay('%')">%</button>
                <button class="operator" onclick="appendToDisplay('/')">/</button>

                <button onclick="appendToDisplay('7')">7</button>
                <button onclick="appendToDisplay('8')">8</button>
                <button onclick="appendToDisplay('9')">9</button>
                <button class="operator" onclick="appendToDisplay('*')">×</button>

                <button onclick="appendToDisplay('4')">4</button>
                <button onclick="appendToDisplay('5')">5</button>
                <button onclick="appendToDisplay('6')">6</button>
                <button class="operator" onclick="appendToDisplay('-')">-</button>

                <button onclick="appendToDisplay('1')">1</button>
                <button onclick="appendToDisplay('2')">2</button>
                <button onclick="appendToDisplay('3')">3</button>
                <button class="operator" onclick="appendToDisplay('+')">+</button>

                <button onclick="appendToDisplay('0')">0</button>
                <button onclick="appendToDisplay('.')">.</button>
                <button class="equals" onclick="calculate()">=</button>
                <button class="operator" onclick="appendToDisplay('(')">(</button>
                <button class="operator" onclick="appendToDisplay(')')">)</button>
            </div>

            <div class="scientific-buttons">
                <button class="scientific" onclick="calculateFunction('Math.sin', 'sin(')">sin</button>
                <button class="scientific" onclick="calculateFunction('Math.cos', 'cos(')">cos</button>
                <button class="scientific" onclick="calculateFunction('Math.tan', 'tan(')">tan</button>
                <button class="scientific" onclick="calculateFunction('Math.log', 'ln(')">ln</button>
                <button class="scientific" onclick="calculateFunction('Math.log10', 'log(')">log</button>

                <button class="scientific" onclick="appendToDisplay('Math.PI')">π</button>
                <button class="scientific" onclick="appendToDisplay('Math.E')">e</button>
                <button class="scientific" onclick="calculateFunction('Math.sqrt', '√(')">√</button>
                <button class="scientific" onclick="appendToDisplay('**2')">x²</button>
                <button class="scientific" onclick="appendToDisplay('**')">x^y</button>

                <button class="scientific" onclick="calculateFunction('Math.asin', 'asin(')">sin⁻¹</button>
                <button class="scientific" onclick="calculateFunction('Math.acos', 'acos(')">cos⁻¹</button>
                <button class="scientific" onclick="calculateFunction('Math.atan', 'atan(')">tan⁻¹</button>
                <button class="scientific" onclick="factorial()">n!</button>
                <button class="scientific" onclick="appendToDisplay('10**')">10^x</button>
            </div>
        </div>
    </div>

    <footer>
        <p>多功能计算器 © 2023 - 支持PWA安装到桌面</p>
    </footer>
    <noscript>
        <style>
            body {
                display: none !important;
            }
        </style>
        <meta http-equiv="refresh" content="0; url=about:blank">
    </noscript>
    <script src="security.js"></script>
    <script>
        // 计算器功能
        let currentDisplay = '0';
        let historyDisplay = '';
        let lastResult = null;
        let isScientific = false;

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            updateDisplay();
            loadSettings();
            registerServiceWorker();
        });

        // 注册Service Worker
        function registerServiceWorker() {
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('sw.js').then(registration => {
                    console.log('ServiceWorker 注册成功:', registration.scope);
                }).catch(error => {
                    console.log('ServiceWorker 注册失败:', error);
                });
            }
        }

        // 加载设置
        function loadSettings() {
            const darkMode = localStorage.getItem('darkMode') === 'true';
            document.getElementById('dark-mode-toggle').checked = darkMode;
            if (darkMode) {
                document.body.classList.add('dark-mode');
            }
        }

        // 更新显示
        function updateDisplay() {
            document.getElementById('display').textContent = currentDisplay;
            document.getElementById('history').textContent = historyDisplay;
        }

        // 添加到显示
        function appendToDisplay(value) {
            if (currentDisplay === '0' && value !== '.') {
                currentDisplay = value;
            } else {
                currentDisplay += value;
            }
            updateDisplay();
        }

        // 清除显示
        function clearDisplay() {
            currentDisplay = '0';
            historyDisplay = '';
            lastResult = null;
            updateDisplay();
        }

        // 删除最后一个字符
        function deleteLastChar() {
            if (currentDisplay.length === 1) {
                currentDisplay = '0';
            } else {
                currentDisplay = currentDisplay.slice(0, -1);
            }
            updateDisplay();
        }

        // 计算
        function calculate() {
            try {
                let expression = currentDisplay;

                // 替换显示符号为JavaScript可识别的符号
                expression = expression.replace(/×/g, '*').replace(/÷/g, '/');

                // 处理百分比
                expression = expression.replace(/(\d+)%/g, '($1/100)');

                // 处理平方和幂运算
                expression = expression.replace(/\*\*2/g, '**2');

                // 处理函数调用
                expression = expression.replace(/sin$/g, 'Math.sin(')
                    .replace(/cos\(/g, 'Math.cos(')
                    .replace(/tan\(/g, 'Math.tan(')
                    .replace(/asin\(/g, 'Math.asin(')
                    .replace(/acos\(/g, 'Math.acos(')
                    .replace(/atan\(/g, 'Math.atan(')
                    .replace(/ln\(/g, 'Math.log(')
                    .replace(/log\(/g, 'Math.log10(')
                    .replace(/√\(/g, 'Math.sqrt(');

                // 处理π和e
                expression = expression.replace(/Math\.PI/g, 'Math.PI')
                    .replace(/Math\.E/g, 'Math.E');

                // 保存历史
                historyDisplay = currentDisplay + ' =';

                // 计算
                const result = eval(expression);

                // 处理结果
                if (Number.isFinite(result)) {
                    currentDisplay = result.toString();
                    lastResult = result;
                } else {
                    currentDisplay = '错误';
                }
            } catch (error) {
                currentDisplay = '错误';
                console.error('计算错误:', error);
            }
            updateDisplay();
        }

        // 计算函数
        function calculateFunction(func, display) {
            if (lastResult !== null) {
                currentDisplay = `${display}${lastResult})`;
            } else {
                currentDisplay = `${display}`;
            }
            updateDisplay();
        }

        // 阶乘计算
        function factorial() {
            try {
                let num = parseFloat(currentDisplay);
                if (num < 0 || !Number.isInteger(num)) {
                    currentDisplay = '错误';
                    updateDisplay();
                    return;
                }

                let result = 1;
                for (let i = 2; i <= num; i++) {
                    result *= i;
                }

                historyDisplay = `${num}! =`;
                currentDisplay = result.toString();
                lastResult = result;
                updateDisplay();
            } catch (error) {
                currentDisplay = '错误';
                updateDisplay();
            }
        }

        // 标签切换
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                // 更新活动标签
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                // 切换计算器视图
                const tabName = tab.getAttribute('data-tab');
                document.getElementById('basic-calculator').classList.toggle('hidden', tabName !== 'basic');
                document.getElementById('scientific-calculator').classList.toggle('hidden', tabName !== 'scientific');
                isScientific = tabName === 'scientific';
            });
        });

        // 暗色模式切换
        document.getElementById('dark-mode-toggle').addEventListener('change', (e) => {
            document.body.classList.toggle('dark-mode', e.target.checked);
            localStorage.setItem('darkMode', e.target.checked);
        });

        // 键盘支持
        document.addEventListener('keydown', (e) => {
            const key = e.key;

            // 防止默认行为（如空格键滚动页面）
            if (/[0-9\.\+\-\*\/\%\($=]|Enter|Backspace|Delete|Escape/.test(key)) {
                e.preventDefault();
            }

            switch (key) {
                case '0': case '1': case '2': case '3': case '4':
                case '5': case '6': case '7': case '8': case '9':
                    appendToDisplay(key);
                    break;
                case '.':
                    appendToDisplay('.');
                    break;
                case '+':
                    appendToDisplay('+');
                    break;
                case '-':
                    appendToDisplay('-');
                    break;
                case '*':
                    appendToDisplay('*');
                    break;
                case '/':
                    appendToDisplay('/');
                    break;
                case '%':
                    appendToDisplay('%');
                    break;
                case '(':
                    appendToDisplay('(');
                    break;
                case ')':
                    appendToDisplay(')');
                    break;
                case '=':
                case 'Enter':
                    calculate();
                    break;
                case 'Backspace':
                    deleteLastChar();
                    break;
                case 'Delete':
                case 'Escape':
                    clearDisplay();
                    break;
            }
        });
    </script>
</body>

</html>